<div class="page-container">
	<h1 class="header"><i><?php echo $this->news->title ?></i></h1>
	<div class="content"><?php
        preg_match_all('/\$(audio|video)\=([a-zA-Zа-яА-я0-9_\-\=\+\/\|\?\:\;\.\,\%\&]*)\$/', stripslashes($this->news->content), $m);
        $count = count($m[0]);
        $content = stripslashes($this->news->content);
        for ($i=0; $i<$count; $i++) {
	        if ($m[1][$i] == 'audio') {
		        $content = strtr(
			        $content,
			        array($m[0][$i] => '<audio src="' . $m[2][$i] . '" type="audio/mp3" controls="controls"></audio>')
		        );
	        } elseif ($m[1][$i] == 'video') {
		        $content = strtr(
			        $content,
			        array($m[0][$i] => '<video src="' . $m[2][$i] . '" type="video/mp4" controls="controls"></audio>')
		        );
	        }
        }
        echo strtr($content, array('$stop$' => ''));
    ?>
	</div>
	<div class="info-block">
		<b>Опубликовано:</b> <?php
            $date = new Zend_Date($this->news->created, false, Pidguin_Application::getInstance()->getLocale());
			echo $date->toString('dd MMMM YYYYг. в HH:mm');
        ?>, 
		<b>Автор: </b><?php echo $this->news->findParentRow('Model_User')->name ?>,
		<b>Комментарий: </b><?php $comments = $this->news->findDependentRowset('Model_NewsComments'); echo count($comments) ?>
	</div>
	<div class="comments-wrap">
	    <div class="comments-header">
	        Комментарии
	    </div>
		<div class="comments-list">
	    <?php if (count($comments) <= 0): ?>
	        Новость еще не комментировали
	    <?php else: $i = 1; foreach ($comments as $comment): ?>
	    <div class="comments-body">
			<div class="comment-author">
				<?php 
					$name = '';
					if ($comment->author_id == 1) {
						$name = $comment->name;
					} else {
						$name = $comment->findParentRow('Model_User')->name;
					}
					echo ucfirst($name);
				?>
				<div class="right">
					<a class="a-comment" 
					   href="#comment-<?php echo $i ?>" 
					   name="comment-<?php echo $i ?>"
					   id="comment-<?php echo $i ?>"
					>#<?php echo $i ?></a>
				</div>
			</div>
			<div class="comment-text"><?php echo $comment->text ?></div>
			<div class="comment-info">
				<?php 
					$date = new Zend_Date($comment->created, false, Pidguin_Application::getInstance()->getLocale());
					echo $date->toString('dd MMMM в HH:mm');
				?>
			</div>
		</div>
	    <?php $i++; endforeach; endif; ?>
		</div>
		<div class="commentate-wrap">
		  <textarea class="comment-textarea" placeholder="Введите свой комментарий..." rows="1"></textarea>
		  <?php if ($this->client->user->id == 1): ?>
			<div id="your-name-wrap" style="margin-top: 5px; display: none; ">
				<label for="your-name">Ваше имя: </label><input type="text" name="your-name" id="your-name" />
			</div>
		  <?php endif; ?>
		  <span class="btn" style="margin-top: 5px; display: none;"><button class="primary" onclick="say(this); return false;">Сказать</button></span>
		  <span id="progress_ajax" style="display: none; margin-top: 5px;" class="progress ajax-preloader-base"></span>
		</div>
	</div>
</div>
<script>
var ct = $('.comment-textarea');
var btn = $('.commentate-wrap .btn');
var ynw = $('#your-name-wrap');
var yn = $('#your-name');
var preloader = $('#progress_ajax');

ct.focus(function(){
	ct.attr('rows', 5);
});

ct.blur(function(){
	if (!ct.val()) {
		ct.attr('rows', 1);
		btn.hide();
		preloader.hide();
	}
});

ct.keyup(function(){
	if (ct.val().length > 4) {
		ynw.css('display', 'inline');
		btn.show();
	} else {
		ynw.css('display', 'none');
		btn.hide();
		preloader.hide();
	}
});

var cd = new goog.ui.Dialog(null, true);
cd.setTitle('Подтвердите что вы не бот');
cd.setButtonSet(
	new goog.ui.Dialog.ButtonSet()
	.addButton({key: 'accept', caption: 'Подтвердить'}, true)
	.addButton({key: 'update', caption: 'Обновить'}, false)
);
goog.events.listen(cd, goog.ui.Dialog.EventType.SELECT, function(e){
	$(cd.getButtonElement()).find('button').hide();
	$(cd.getButtonElement()).append('<span id="progress_ajax" style="display: block; margin-top: 5px;" class="progress ajax-preloader-base"></span>');
	if (e.key == 'accept') {
		if (!$(cd.getContentElement()).find('#captcha-input').val()) {
			$(cd.getContentElement()).find('#captcha-input').focus();
			return false;
		}
		$.post('/news/comment.add', {
			'captcha[id]': $(cd.getContentElement()).find('#captcha-id').val(),
			'captcha[input]': $(cd.getContentElement()).find('#captcha-input').val(),
			'news_id': $(cd.getContentElement()).find('#news_id').val(),
			'name': $(cd.getContentElement()).find('#name').val(),
			'text': $(cd.getContentElement()).find('#text').val()
		}, function(response){
			if (typeof response.form == 'string') {
				$('#comment-add-accept-captcha-form').parent().parent().find('dd').eq(0).html(response.form);
				$(cd.getButtonElement()).find('button').show();
				$(cd.getButtonElement()).find('#progress_ajax').hide();
				return false;
			} else {
				addComment(response.comment);
				cd.setVisible(false);
				return true;
			}
		}, 'json');
		return false;
	} else if(e.key == 'update') {
		$.getJSON('/captcha/update', {}, function(response){
			$('#comment-add-accept-captcha-form').parent().parent().find('dd').eq(0).html(response.form);
			$(cd.getButtonElement()).find('button').show();
			$(cd.getButtonElement()).find('#progress_ajax').hide();
		});
		return false;
	}
});
function say(el) {
	if (!ct.val()) {
		ct.focus();
		return false;
	}
	if (yn.length == 1) {
		if (!yn.val()) {
			yn.focus();
			return false;
		}
	}
	ct.attr('disabled', 'disabled');
	yn.attr('disabled', 'disabled');
	$(el).parent().hide();
	preloader.show();
	$.ajax({
		'url': '/news/comment.add',
		'type': 'post',
		'data': {
			'news_id': <?php echo $this->news->id ?>,
			'name': (yn.length == 1) ? yn.val() : '',
			'text': ct.val()
		},
		'dataType': 'json',
		'success': function(response) {
			/**
			 * если пришла капча то показываем окно
			 */
			if (typeof response.captcha_form != 'undefined') {
				cd.setContent(response.captcha_form);
				cd.setVisible(true);
				$(cd.getElement()).css({'width': '350px', 'left': (document.width / 2) - 175 + 'px'});
				$('#comment-add-accept-captcha-form').parent().parent().find('dt,dd').hide();
				$('#comment-add-accept-captcha-form').parent().parent().find('dd').eq(0).show().attr('align', 'center');
			} else {
				addComment(response.comment);
			}
			ct.removeAttr('disabled');
			yn.removeAttr('disabled');
			$(el).parent().show();
			preloader.hide();
		},
		'error': function(error) {
			alert('При обработке запроса возникли какие-то ошибки');
			ct.removeAttr('disabled');
			yn.removeAttr('disabled');
			$(el).parent().show();
			preloader.hide();
		}
	});
}

function addComment(data) {
	var i = $('.comments-list .comments-body').length + 1;
	var html = '<div class="comments-body"><div class="comment-author">' + data.name + '<div class="right">';
	html += '<a class="a-comment" href="#comment-' + i + '" name="comment-' + i + '" id="comment-' + i + '">#' + i + '</a></div></div>';
	html += '<div class="comment-text">' + data.text + '</div>';
	html += '<div class="comment-info">' + data.created + '</div></div>';
	$('.comments-list').append(html);
	ct.val('');
}
</script>